package com.itheima.ydd.controller;

import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.entity.FileResult;
import com.itheima.ydd.utils.QiniuCloudUtil;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.UUID;

/**
 * Copyright (C), 2021-2022
 * Author: 16372
 * Date: 2022/2/28 18:02
 * FileName: CommonController
 * Description: 图片资源管理
 */
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${ydd.path}")
    private String basePath;
    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public ResultData upload(MultipartFile file,String type){
        FileResult fileResult = new FileResult();
        //file是一个临时文件，需要转存到指定位置，否则本次请求完成后临时文件会删除
        //log.info(file.toString());
        if (type == "images"){
            fileResult.setMime("image/jpeg");
        }
        //原始文件名
        String originalFilename = file.getOriginalFilename();//abc.jpg
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //使用UUID重新生成文件名，防止文件名称重复造成文件覆盖
        String fileName = UUID.randomUUID().toString() + suffix;//dfsdfdfd.jpg
        //String fileName = "lstp" + suffix;

        try {
            fileResult.setName(fileName);
            //将文件转存到指定位置
            String image = QiniuCloudUtil.put64image(file.getBytes(), fileName); // udfindupload/qn.zcscloud.cn/fileName ==> http://qn.zcscloud.cn/fileName
            System.out.println("image = " + image);
            fileResult.setSavePath(image);
            //log.info("本地保存成功,路径名:{}<=========================================",basePath + fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultData.ok("",fileResult);
    }


    /**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            InputStream inputStream = null;
            if (name.contains("lstp")){
                inputStream = new FileInputStream(new File(basePath + name));
                //log.info("本地图片{}加载成功<=================================",basePath + name);
            }else {
                String fileUrl = "http://" + name;
                //使用url替代获取然后转换成流即可
                URL url = new URL(fileUrl);
                inputStream = url.openStream();
                //log.info("服务器图片{}加载成功<==================================",fileUrl);
            }
            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("image/jpeg");

            IOUtils.copy(inputStream,outputStream);
            //关闭资源
            outputStream.close();
            inputStream.close();
        } catch (Exception e) {
            System.out.println("资源不存在");
        }
    }
}
